package dao

import (
	"context"
	"mpps/tools/config"
	"mpps/tools/repository/dao/program"
	"mpps/tools/repository/dao/user"
	"time"

	log "github.com/asim/go-micro/v3/logger"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

var gormDB *gorm.DB

func init() {
	var dsn = config.G_mysqldsn
	var ormLogger logger.Interface
	if config.G_runmode == "prod" {
		ormLogger = logger.Default
	} else {
		ormLogger = logger.Default.LogMode(logger.Info)
	}

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger:         ormLogger,
		NamingStrategy: schema.NamingStrategy{
			// TablePrefix:   "tb_",
			// SingularTable: true,
		},
	})
	if err != nil {
		log.Infof("%v %v", err, dsn)
		panic(err)
	}

	sqlDB, err := db.DB()
	sqlDB.SetMaxIdleConns(20)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)
	// defer sqlDB.Close()

	if err != nil {
		log.Fatal(err)
		panic(err)
	}

	// 建表
	db.AutoMigrate(
		&program.MiniProgram{},
		&user.User{},
	)

	gormDB = db

	log.Info("db connected success")
}

func GetDB(ctx context.Context) *gorm.DB {
	return gormDB.WithContext(ctx)
}
